<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageNotesApi, readNoteApi, oneNoteApi, proNotesApi } from '@/commons/api'
import routes from '@/commons/router'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager.vue'
import Datepicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'
import { formatDate, formatDateRange } from '@/commons/filter'
import { CScrollbar } from 'c-scrollbar'
import Loader from '@/components/loader/Loader.vue'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let userId = ''
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      userId = res.data.userId
      await list(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const dates = ref([])
const schObj = {
  keywords: '',
  userId: userId,
  beginTime: 0,
  endTime: 0,
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const noteList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  schRef.value.beginTime = dates.value && dates.value.length===2 && dates.value[0] ? dates.value[0].getTime()/1000 : 0
  schRef.value.endTime = dates.value && dates.value.length===2 && dates.value[1] ? dates.value[1].getTime()/1000 : 0
  const res = await pageNotesApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    noteList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    userId: userId,
    beginTime: 0,
    endTime: 0,
    offset: 0,
    limit: 20
  }
  dates.value = []
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    noteList.value.forEach(item => {
      idList.value.push(item.relId)
      checkList.value.push(true)
    })
  } else {
    noteList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, relId) => {
  if(!checkList.value[idx]) {
    idList.value.push(relId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === relId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

// detail 消息详情
const noteRef = ref({
  noteId: '',
  title: '',
  contents: '',
  addTime: 0
})
const showModal = ref(false)
// readNote 已读消息
const readNote = async (relId, noteId) => {
  loadShow.value = true
  try {
    const res = await readNoteApi({ relId })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await detail(noteId)
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}
const detail = async (noteId) => {
  loadShow.value = true
  try {
    const res = await oneNoteApi({ noteId })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
      noteRef.value = res.data
      showModal.value = true
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  list(0, 1)
  showModal.value = false
  noteRef.value = null
}

// process 删除消息
const process = (states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要处理选中的消息吗？').then(() => {
    procNotes(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的消息！" })
  })
}
// procNotes 删除消息实现，分离出来防止调用时异步报错
const procNotes = async (states) => {
  const relIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proNotesApi({ states, relIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，消息处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})

// stateFmt 状态转码
const stateFmt = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '未读'
        break;
      case 2:
        str = '已读'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div class="btn-pi mr15" title="已读" @click="process(1)"><i class="iconfont">&#xea2d;</i> 已读</div>
        <div class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 消息管理</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="mr15 mt10"><Datepicker v-model="dates" range locale="zh-CN" :format="formatDateRange" style="width: 250px;" placeholder="请选择筛选时间段" /></div>
      <div class="f mt10">
        <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 5%;"><span @click="checkAll()" title="全选"><i class="iconfont fs20 cur" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 50%;">标题</th>
            <th style="width: 25%;">时间</th>
            <th style="width: 15%;">状态</th>
          </tr>
          <tr v-for="(curNote, index) in noteList" :key="curNote.relId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curNote.relId)" title="选择"><i class="iconfont fs18 cur" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td><a href="javascript:void(0);" class="cl-blue" @click="readNote(curNote.relId, curNote.noteId)">{{curNote.title}}</a></td>
            <td class="txt-center">{{fmtDate(curNote.addTime, 2)}}</td>
            <td class="txt-center"><span :class="[curNote.states===1 ? 'tag-s' : 'tag-e']">{{stateFmt(curNote.states)}}</span></td>
          </tr>
        </tbody>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 800px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 消息详情</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title">消息标题</div>
                <div class="g">{{noteRef.title}}</div>
              </div>
              <div>
                <div class="ipt-title">消息内容</div>
                <div class="g">{{noteRef.contents}}</div>
              </div>
              <div>
                <div class="ipt-title">发布时间</div>
                <div class="g">{{fmtDate(noteRef.addTime, 2)}}</div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.f {display: inline-flex; display: -webkit-inline-flex;}
</style>